package com.lincoln.framework.tag;

import com.lincoln.framework.common.WebUtils;
import com.lincoln.framework.hibernate.Page;
import com.lincoln.framework.utils.ParameterChecker;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
import java.io.IOException;

/**
 * 前台排序标签
 * @author jared
 *
 */
public class SiteSortColumnTag extends TagSupport{
	
	/**
	 *	排序列数据库字段
	 */
	private String sortAttr;
	
	/**
	 * 列名称
	 */
	private String columnName;

	/**
	 * 表名
	 */
	private String targetForm;
	
	/**
	 * 排序样式：(up,down)
	 */
	private String sortClass;
	
	private Page pageObj;
	
	public int doStartTag() throws JspException { 
        JspWriter out = pageContext.getOut();
        try{
        	//判断结果集信息
			StringBuilder sb = new StringBuilder();
			String alinkName = "column_"+targetForm.trim()+"_"+sortAttr.replace(".", "_");
			String upClass = "up_white";
			String downClass = "down_white";
			if(!ParameterChecker.isNullOrEmpty(sortClass)) {
				upClass = sortClass.split(",")[0];
				downClass = sortClass.split(",")[1];
			}
			if (pageObj != null) {
				if (isOrderByCurrentColumn(pageObj)) {
					if (pageObj.getOrder().equals(Page.ASC)) {
						sb.append("<a id=" + alinkName + " href=\"javascript:sitesortcolumn('" + targetForm.trim() + "','" + sortAttr + "','desc')\" >" + WebUtils.getLocaleMessage(columnName) + "<i class=\""+ upClass +"\"></i></a>");
					} else {
						sb.append("<a id=" + alinkName + "  href=\"javascript:sitesortcolumn('" + targetForm.trim() + "','" + sortAttr + "','asc')\" >" + WebUtils.getLocaleMessage(columnName) + "<i class=\""+ downClass +"\"></i></a>");
					}
				}else{
					sb.append("<a id=" + alinkName + " href=\"javascript:sitesortcolumn('" + targetForm.trim() + "','" + sortAttr + "','desc')\" >" + WebUtils.getLocaleMessage(columnName) + "</a>");
				}
			} else {
				sb.append(WebUtils.getLocaleMessage(columnName));
			}
        	out.print(sb);
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        return super.doStartTag();  
  
	}
	
	//判断当前form查询是否按照当前列进行排序
	private boolean isOrderByCurrentColumn(Page pageObj){
		return !ParameterChecker.isNullOrEmpty(pageObj.getOrderBy()) && pageObj.getOrderBy().equals(sortAttr);
	}

	public String getSortAttr() {
		return sortAttr;
	}

	public void setSortAttr(String sortAttr) {
		this.sortAttr = sortAttr;
	}

	public String getColumnName() {
		return columnName;
	}

	public void setColumnName(String columnName) {
		this.columnName = columnName;
	}

	public String getTargetForm() {
		return targetForm;
	}

	public void setTargetForm(String targetForm) {
		this.targetForm = targetForm;
	}

	public Page getPageObj() {
		return pageObj;
	}

	public void setPageObj(Page pageObj) {
		this.pageObj = pageObj;
	}

	public String getSortClass() {
		return sortClass;
	}

	public void setSortClass(String sortClass) {
		this.sortClass = sortClass;
	}
}
